package cate.game.role.farm.forbidden;

import cate.common.table.d.GDFight;
import cate.common.table.d.GDForbidden;
import cate.common.table.d.GDOperation;
import cate.common.table.farm.forbidden.row.ForbiddenCombatRow;
import cp.solution.util.time.TimeSpanCheck;
import cate.game.play.proce.play.PlayPO;
import cate.game.res.MixRes;
import cate.game.res.MixResAdder;
import cate.game.role.Role;
import cate.game.role.farm.AbstractFarmFTC;
import cate.game.role.farm.forbidden.msg.ForbiddenChallengeResultResp;
import cate.game.role.farm.forbidden.msg.ForbiddenDataUpdateResp;
import cate.game.role.farm.forbidden.msg.ForbiddenOneResp;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ForbiddenFTC extends AbstractFarmFTC {

    /**
     * 当前挑战关卡的模板
     */
    private ForbiddenCombatRow tpl;

    private long createTime;

    private boolean auto;

    public ForbiddenFTC(Role role, ForbiddenCombatRow tpl, boolean auto) {
        setup(role);
        this.createTime = System.currentTimeMillis();
        this.tpl = tpl;
        this.auto = auto;
    }


    @Override
    public void handleResult(Role role, PlayPO play) {
        super.handleResult(role, play);
        boolean win = play.winner == GDFight.Team.A;
        ForbiddenChallengeResultResp resultResp = new ForbiddenChallengeResultResp();
        resultResp.win = win;
        resultResp.funcId = GDForbidden.Type.toFuncId(tpl.roomId);
        resultResp.passFloor = tpl.combatNum;
        boolean spanWeek = TimeSpanCheck.spanWeek(this.createTime);
        boolean spanDay = TimeSpanCheck.spanWeek(this.createTime);

        if (win) {
            po(role).playTimes.added();
            ForbiddenPO fb = po(role).getFb(tpl.roomId);
            if (!spanWeek || !spanDay) {
                fb.setPassSafe(this.tpl.combatNum);
            }
            fb.addScore(tpl.passScore, this.createTime);
            role.sendNow(new ForbiddenOneResp(fb));
            resultResp.passFloor = tpl.combatNum;
            if (!auto) {
                //非一键战斗 只有一场
                resultResp.reward = new MixRes(this.tpl.rewardFirstStr);
                MixResAdder mra =
                        new MixResAdder()
                                .setRes(resultResp.reward)
                                .setOperation(GDOperation.FORBIDDEN_CHALLENGE);
                mra.exe(role);
            }
            if (spanWeek) {
                log.info("出现跨周的情况导致记录丢失 玩家ID {}", role.getUid());
            }

            role.getHistory().action.passForbidden();
        }

        if (!auto) {
            role.sendNow(new ForbiddenDataUpdateResp(role));
            role.sendNow(resultResp);
            role.sendNow(new ForbiddenOneResp(po(role).getFb(tpl.roomId)));
        }
    }

    @Override
    protected MyForbiddenZone po(Role role) {
        return role.getFarm().forbidden;
    }
}
